﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CDSBDemandControlService
{
    public class Cryptography
    {
        public static Byte[] key = new Byte[] { 34, 56, 23, 77, 42, 45, 78, 8 };

        /// <summary>
        /// Criptografar um string utilizando a chave de criptografia informada
        /// </summary>
        /// <param name="data">String a ser criptografada</param>
        /// <param name="key">Chave de criptografia</param>
        /// <returns></returns>
        public static string Encrypt(string data)
        {
            if (data == null)
                throw new ArgumentNullException("data");

            if (key == null)
                throw new ArgumentNullException("key");

            byte[] keyCopy = new byte[key.Length];
            key.CopyTo(keyCopy, 0);

            byte[] encryptedData = null;

            ProtectedKey protectedKey = ProtectedKey.Create(keyCopy);
            SymmetricCryptographer cryptographer = new SymmetricCryptographer(SymmetricCryptographer.Algorithm.DES, protectedKey);

            //string para bytes
            //Criptografa
            encryptedData = cryptographer.Encrypt(Encoding.Unicode.GetBytes(data));

            //bytes para string
            return Convert.ToBase64String(encryptedData);
        }

        /// <summary>
        /// Decriptografar um string utilizando a chave de criptografia informada
        /// </summary>
        /// <param name="encryptedData">String a ser decriptografada</param>
        /// <param name="key">Chave de criptografia</param>
        /// <returns></returns>
        public static string Decrypt(string encryptedData)
        {
            if (encryptedData == null)
                throw new ArgumentNullException("data");

            if (key == null)
                throw new ArgumentNullException("key");

            byte[] keyCopy = new byte[key.Length];
            key.CopyTo(keyCopy, 0);

            byte[] decryptedData = null;

            ProtectedKey protectedKey = ProtectedKey.Create(keyCopy);
            SymmetricCryptographer cryptographer = new SymmetricCryptographer(SymmetricCryptographer.Algorithm.DES, protectedKey);

            decryptedData = cryptographer.Decrypt(Convert.FromBase64String(encryptedData));

            //bytes para string
            return Encoding.Unicode.GetString(decryptedData);
        }
    }
}
